package cn.javadog.algorithm.m1_100;


/**
 * 字符串转换整数 (atoi)
 * https://leetcode-cn.com/problems/string-to-integer-atoi/
 * @author Sprite
 */
public class Algorithm8 {
	public static void main(String[] args) {
		System.out.println(myAtoi("words and 987"));
		System.out.println(myAtoi(" 42"));
		System.out.println(myAtoi("-91283472332"));
		System.out.println(myAtoi(" b11228552307"));
	}

	public static int myAtoi(String str) {
		if (str.length() == 0) return 0;
		char[] cc = str.toCharArray();
		int f = 0;
		int startIdx = -1;
		long res = 0;
		for (int i = 0; i < cc.length; i++) {
			if (cc[i] == ' ') continue;

			if (cc[i] == '+'){
				f = 1;
				startIdx = ++i;
				break;
			}else if (cc[i] == '-'){
				f = -1;
				startIdx = ++i;
				break;
			}else if ( Character.isDigit(cc[i])){
				f = 1;
				startIdx = i;
				break;
			}else {
				break;
			}
		}

		if (startIdx == -1) return 0;

		for (int i = startIdx; i < cc.length; i++) {
			if (!Character.isDigit(cc[i])){
				return (int) (res * f);
			}
			res = 10 * res + cc[i] - '0';
			if (res * f >= Integer.MAX_VALUE) {
				return Integer.MAX_VALUE;
			}else if (res * f <= Integer.MIN_VALUE){
				return Integer.MIN_VALUE;
			}
		}
		return (int) (res * f);
	}
}
